using APP.HELPER.Data.Helper;
using APP.HELPER.Utils.Language;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using Extra.Data.Extra;
using Extra.Data.Extra.Class;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using System;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Windows.Forms;
namespace Extra.Data.Core
{
    public class xfmRestoreDatabase : XtraForm
    {
        private readonly string _connectionString;
        private readonly string _database;
        private ProgressBarControl Bar;
        private SimpleButton btnClose;
        private SimpleButton btnHelp;
        private SimpleButton btnStart;
        private IContainer components = null;
        private GroupControl groupControl1;
        private LabelControl lblDatabaseName;
        private LabelControl lblDetail;
        private LabelControl lblFileName;
        private LabelControl lblMessage;
        private LabelControl lblProgress;
        private PictureBox pictureBox1;
        private ButtonEdit txtBackupFile;
        private TextEdit txtBackupFolder;

        public event RestoreCompleteEventHander RestoreComplete;

        public event RestoreErrorEventHander RestoreError;

        public event RestoreProcessEventHander RestoreProcess;

        public xfmRestoreDatabase()
        {
            this.InitializeComponent();
            this.InitMultiLanguages();
            SqlHelper helper = new SqlHelper(SqlHelper.ConnectString);
            helper.Extract();
            this._connectionString = string.Format("data source={0};integrated security=SSPI;Initial Catalog=master;", helper.Server);
            if (!helper.Authentication)
            {
                this._connectionString = string.Format("server={0};user id={1};password={2};", helper.Server, helper.UserID, helper.Password);
            }
            this._database = helper.Database;
            this.txtBackupFolder.Text = @"D:\Database\Perfect Software\Perfect HRM 2012";
            this.txtBackupFolder.Text = this._database;
        }

        private void btnBackupFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog
            {
                Filter = "Backup File(*.bak)|*.bak|All File(*.*)|*.*",
                FilterIndex = 0
            };
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                SqlConnection sqlConnection = new SqlConnection(this._connectionString);
                sqlConnection.Open();
                ServerConnection serverConnection = new ServerConnection(sqlConnection);
                Server server = new Server(serverConnection);
                Database database = server.Databases[this._database];
                if (database != null)
                {
                    this.txtBackupFolder.Text = this._database;
                }
                this.txtBackupFile.Text = dialog.FileName;
                sqlConnection.Close();
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            base.Close();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            this.btnStart.Enabled = false;
            DataController.ConnectString = SqlHelper.ServerConnectString;
            DataController restore = new DataController();
            this.groupControl1.Text = "Đang Phục Hồi...";
            restore.RestoreComplete += new RestoreCompleteEventHander(this.restore_RestoreComplete);
            restore.RestoreError += new RestoreErrorEventHander(this.restore_RestoreError);
            restore.RestoreProcess += new RestoreProcessEventHander(this.restore_RestoreProcess);
            new Thread(() => restore.RestoreDatabase(this.txtBackupFile.Text, this.txtBackupFolder.Text)).Start();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (this.components != null))
            {
                this.components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            ComponentResourceManager manager = new ComponentResourceManager(typeof(xfmRestoreDatabase));
            SerializableAppearanceObject appearance = new SerializableAppearanceObject();
            this.Bar = new ProgressBarControl();
            this.txtBackupFolder = new TextEdit();
            this.lblDatabaseName = new LabelControl();
            this.lblFileName = new LabelControl();
            this.txtBackupFile = new ButtonEdit();
            this.lblProgress = new LabelControl();
            this.groupControl1 = new GroupControl();
            this.pictureBox1 = new PictureBox();
            this.btnHelp = new SimpleButton();
            this.btnClose = new SimpleButton();
            this.btnStart = new SimpleButton();
            this.lblMessage = new LabelControl();
            this.lblDetail = new LabelControl();
            this.Bar.Properties.BeginInit();
            this.txtBackupFolder.Properties.BeginInit();
            this.txtBackupFile.Properties.BeginInit();
            this.groupControl1.BeginInit();
            this.groupControl1.SuspendLayout();
            ((ISupportInitialize)this.pictureBox1).BeginInit();
            base.SuspendLayout();
            this.Bar.Location = new Point(0x40, 11);
            this.Bar.Name = "Bar";
            this.Bar.Properties.ShowTitle = true;
            this.Bar.Size = new Size(0x142, 0x13);
            this.Bar.TabIndex = 15;
            this.txtBackupFolder.Enabled = false;
            this.txtBackupFolder.Location = new Point(0x40, 0x47);
            this.txtBackupFolder.Name = "txtBackupFolder";
            this.txtBackupFolder.Size = new Size(0x142, 20);
            this.txtBackupFolder.TabIndex = 13;
            this.lblDatabaseName.Location = new Point(6, 0x49);
            this.lblDatabaseName.Name = "lblDatabaseName";
            this.lblDatabaseName.Size = new Size(0x35, 13);
            this.lblDatabaseName.TabIndex = 12;
            this.lblDatabaseName.Text = "T\x00ean dữ liệu";
            this.lblFileName.Location = new Point(6, 0x2b);
            this.lblFileName.Name = "lblFileName";
            this.lblFileName.Size = new Size(0x34, 13);
            this.lblFileName.TabIndex = 10;
            this.lblFileName.Text = "T\x00ean tập tin";
            this.txtBackupFile.Location = new Point(0x40, 0x27);
            this.txtBackupFile.Name = "txtBackupFile";
            this.txtBackupFile.Properties.Buttons.AddRange(new EditorButton[] { new EditorButton(ButtonPredefines.Glyph, "", -1, true, true, false, ImageLocation.MiddleCenter, (Image)manager.GetObject("txtBackupFile.Properties.Buttons"), new KeyShortcut(System.Windows.Forms.Keys.None), appearance, "", "Browse", null, true) });
            this.txtBackupFile.Properties.ButtonClick += new ButtonPressedEventHandler(this.txtBackupFile_Properties_ButtonClick);
            this.txtBackupFile.Size = new Size(0x142, 0x16);
            this.txtBackupFile.TabIndex = 11;
            this.txtBackupFile.TabStop = false;
            this.lblProgress.Location = new Point(6, 12);
            this.lblProgress.Name = "lblProgress";
            this.lblProgress.Size = new Size(0x2d, 13);
            this.lblProgress.TabIndex = 0x12;
            this.lblProgress.Text = "Tiến tr\x00ecnh";
            this.groupControl1.Appearance.GradientMode = LinearGradientMode.ForwardDiagonal;
            this.groupControl1.AppearanceCaption.Font = new Font("Tahoma", 8.25f, FontStyle.Regular, GraphicsUnit.Point, 0);
            this.groupControl1.AppearanceCaption.ForeColor = Color.SteelBlue;
            this.groupControl1.AppearanceCaption.Options.UseFont = true;
            this.groupControl1.AppearanceCaption.Options.UseForeColor = true;
            this.groupControl1.AppearanceCaption.Options.UseTextOptions = true;
            this.groupControl1.AppearanceCaption.TextOptions.HAlignment = HorzAlignment.Center;
            this.groupControl1.BorderStyle = BorderStyles.NoBorder;
            this.groupControl1.Controls.Add(this.Bar);
            this.groupControl1.Controls.Add(this.txtBackupFile);
            this.groupControl1.Controls.Add(this.lblProgress);
            this.groupControl1.Controls.Add(this.lblFileName);
            this.groupControl1.Controls.Add(this.lblDatabaseName);
            this.groupControl1.Controls.Add(this.txtBackupFolder);
            this.groupControl1.Location = new Point(0x84, 90);
            this.groupControl1.Name = "groupControl1";
            this.groupControl1.ShowCaption = false;
            this.groupControl1.Size = new Size(0x185, 0x62);
            this.groupControl1.TabIndex = 0x1d;
            this.groupControl1.Text = "Phục hồi dữ liệu đ\x00e3 được sao lưu";
            this.pictureBox1.Dock = DockStyle.Left;
            this.pictureBox1.Image = Img.bg_restore;
            this.pictureBox1.Location = new Point(0, 0);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new Size(0x7e, 0x15f);
            this.pictureBox1.TabIndex = 30;
            this.pictureBox1.TabStop = false;
            this.btnHelp.Image = (Image)manager.GetObject("btnHelp.Image");
            this.btnHelp.Location = new Point(0x91, 0x13c);
            this.btnHelp.Name = "btnHelp";
            this.btnHelp.Size = new Size(0x53, 0x17);
            this.btnHelp.TabIndex = 0x1c;
            this.btnHelp.Text = "Trợ Gi\x00fap";
            this.btnClose.Image = (Image)manager.GetObject("btnClose.Image");
            this.btnClose.Location = new Point(0x1bb, 0x13c);
            this.btnClose.Name = "btnClose";
            this.btnClose.Size = new Size(0x4b, 0x17);
            this.btnClose.TabIndex = 0x11;
            this.btnClose.Text = "Đ\x00f3ng";
            this.btnClose.Click += new EventHandler(this.btnClose_Click);
            this.btnStart.Image = (Image)manager.GetObject("btnStart.Image");
            this.btnStart.Location = new Point(0x16a, 0x13c);
            this.btnStart.Name = "btnStart";
            this.btnStart.Size = new Size(0x4b, 0x17);
            this.btnStart.TabIndex = 0x10;
            this.btnStart.Text = "Thực Hiện";
            this.btnStart.Click += new EventHandler(this.btnStart_Click);
            this.lblMessage.Appearance.Font = new Font("Tahoma", 9f, FontStyle.Bold, GraphicsUnit.Point, 0);
            this.lblMessage.Appearance.ForeColor = Color.SteelBlue;
            this.lblMessage.Appearance.Options.UseFont = true;
            this.lblMessage.Appearance.Options.UseForeColor = true;
            this.lblMessage.AutoSizeMode = LabelAutoSizeMode.Vertical;
            this.lblMessage.Location = new Point(0x88, 12);
            this.lblMessage.Name = "lblMessage";
            this.lblMessage.Size = new Size(0x151, 14);
            this.lblMessage.TabIndex = 0x1f;
            this.lblMessage.Text = "Phục hồi dữ liệu đ\x00e3 sao lưu";
            this.lblDetail.Appearance.Options.UseTextOptions = true;
            this.lblDetail.Appearance.TextOptions.WordWrap = WordWrap.Wrap;
            this.lblDetail.AutoSizeMode = LabelAutoSizeMode.None;
            this.lblDetail.Location = new Point(0x88, 0x20);
            this.lblDetail.Name = "lblDetail";
            this.lblDetail.Size = new Size(0x181, 0x20);
            this.lblDetail.TabIndex = 0x22;
            this.lblDetail.Text = "Phục hồi dữ liệu, theo d\x00f5i v\x00e0 kiểm tra thường xuy\x00ean để ph\x00e1t hiện c\x00e1c trục trặc trước khi n\x00f3 xảy ra.";
            base.AutoScaleDimensions = new SizeF(6f, 13f);
            base.AutoScaleMode = AutoScaleMode.Font;
            base.ClientSize = new Size(0x216, 0x15f);
            base.Controls.Add(this.lblDetail);
            base.Controls.Add(this.lblMessage);
            base.Controls.Add(this.pictureBox1);
            base.Controls.Add(this.groupControl1);
            base.Controls.Add(this.btnHelp);
            base.Controls.Add(this.btnClose);
            base.Controls.Add(this.btnStart);
            this.DoubleBuffered = true;
            base.FormBorderStyle = FormBorderStyle.FixedSingle;
            base.MaximizeBox = false;
            base.MinimizeBox = false;
            base.Name = "xfmRestoreDatabase";
            base.ShowIcon = false;
            base.ShowInTaskbar = false;
            base.StartPosition = FormStartPosition.CenterScreen;
            this.Text = "Phục hồi dữ liệu";
            this.Bar.Properties.EndInit();
            this.txtBackupFolder.Properties.EndInit();
            this.txtBackupFile.Properties.EndInit();
            this.groupControl1.EndInit();
            this.groupControl1.ResumeLayout(false);
            this.groupControl1.PerformLayout();
            ((ISupportInitialize)this.pictureBox1).EndInit();
            base.ResumeLayout(false);
            base.PerformLayout();
        }

        private void InitMultiLanguages()
        {
            this.Text = MultiLanguages.GetString("tbl_DatabaseConfig", "RestoreDatabase", "Phục Hồi Dữ Liệu");
            this.lblMessage.Text = MultiLanguages.GetString("tbl_DatabaseConfig", "RestoreDatabaseTitle", "Phục hồi dữ liệu đ\x00e3 sao lưu");
            this.lblDetail.Text = MultiLanguages.GetString("tbl_DatabaseConfig", "RestoreDatabaseDetail", "Phục hồi dữ liệu, theo d\x00f5i v\x00e0 kiểm tra thường xuy\x00ean để ph\x00e1t hiện c\x00e1c trục trặc trước khi n\x00f3 xảy ra.");
            this.lblProgress.Text = MultiLanguages.GetString("tbl_DatabaseConfig", "Progress", "Tiến tr\x00ecnh");
            this.lblFileName.Text = MultiLanguages.GetString("tbl_DatabaseConfig", "FileName", "T\x00ean tập tin");
            this.lblDatabaseName.Text = MultiLanguages.GetString("tbl_DatabaseConfig", "Database", "T\x00ean dữ liệu");
            this.btnStart.Text = MultiLanguages.GetString("tbl_DatabaseConfig", "Action", "Thực Hiện");
            this.btnHelp.Text = MultiLanguages.GetString("tbl_DatabaseConfig", "Help", "Trợ Gi\x00fap");
            this.btnClose.Text = MultiLanguages.GetString("tbl_DatabaseConfig", "Close", "Đ\x00f3ng");
        }

        protected override bool ProcessDialogKey(System.Windows.Forms.Keys keyData)
        {
            if (keyData == System.Windows.Forms.Keys.Escape)
            {
                base.Close();
                return true;
            }
            return false;
        }

        private void RaiseRestoreCompleteEventHander(ServerMessageEventArgs e)
        {
            if (this.RestoreComplete != null)
            {
                this.RestoreComplete(this, e);
            }
        }

        private void RaiseRestoreErrorEventHander(string message)
        {
            if (this.RestoreError != null)
            {
                this.RestoreError(this, message);
            }
        }

        private void RaiseRestoreProcessEventHander(PercentCompleteEventArgs e)
        {
            if (this.RestoreProcess != null)
            {
                this.RestoreProcess(this, e);
            }
        }

        private void restore_RestoreComplete(object sender, ServerMessageEventArgs e)
        {
            if (this.Bar.InvokeRequired)
            {
                RestoreCompleteEventHander method = new RestoreCompleteEventHander(this.restore_RestoreComplete);
                base.Invoke(method, new object[] { sender, e });
            }
            else
            {
                this.Bar.EditValue = 0;
                this.btnStart.Enabled = true;
                this.groupControl1.Text = "Phục Hồi Th\x00e0nh C\x00f4ng.";
                XtraMessageBox.Show("Phục Hồi Th\x00e0nh C\x00f4ng.\nĐể cập nhật mới dữ liệu, phần mềm sẽ khởi động lại.", "Th\x00f4ng B\x00e1o", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                Application.Restart();
            }
            this.RaiseRestoreCompleteEventHander(e);
        }

        private void restore_RestoreError(object sender, string Message)
        {
            if (this.Bar.InvokeRequired)
            {
                RestoreErrorEventHander method = new RestoreErrorEventHander(this.restore_RestoreError);
                base.Invoke(method, new object[] { sender, Message });
            }
            else
            {
                XtraMessageBox.Show("Error:\n\t" + Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                this.btnStart.Enabled = true;
                this.Bar.EditValue = 0;
            }
            this.RaiseRestoreErrorEventHander(Message);
        }

        private void restore_RestoreProcess(object sender, PercentCompleteEventArgs e)
        {
            if (this.Bar.InvokeRequired)
            {
                RestoreProcessEventHander method = new RestoreProcessEventHander(this.restore_RestoreProcess);
                base.Invoke(method, new object[] { sender, e });
            }
            else
            {
                this.Bar.EditValue = e.Percent;
            }
            this.RaiseRestoreProcessEventHander(e);
        }

        private void txtBackupFile_Properties_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog
            {
                Filter = "Backup File(*.bak)|*.bak|All File(*.*)|*.*",
                FilterIndex = 0
            };
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                SqlConnection sqlConnection = new SqlConnection(this._connectionString);
                sqlConnection.Open();
                ServerConnection serverConnection = new ServerConnection(sqlConnection);
                Server server = new Server(serverConnection);
                Database database = server.Databases[this._database];
                if (database != null)
                {
                    this.txtBackupFolder.Text = this._database;
                }
                this.txtBackupFile.Text = dialog.FileName;
                sqlConnection.Close();
            }
        }
    }

}
